import { Config, Inject, Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { BizCustomerWorkerCollectionEntity } from '../entity/workerCollection';
import { BizWorkerListEntity } from '../../bizWorker/entity/list';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { In, Repository } from 'typeorm';

/**
 * 客户收藏师傅列表服务
 */
@Provide()
export class BizCustomerWorkerCollectionService extends BaseService {
  @InjectEntityModel(BizCustomerWorkerCollectionEntity)
  bizCustomerWorkerCollectionEntity: Repository<BizCustomerWorkerCollectionEntity>;
  @InjectEntityModel(BizWorkerListEntity)
  bizWorkerListEntity: Repository<BizWorkerListEntity>;

  async pageAndWorkerInfo(page: number, size: number, userId: number) {
    const pageData = await this.page({ page, size, userId }, {});
    const workerIds = pageData.list.map(v => v.workerId);

    pageData.list = await this.bizWorkerListEntity.findBy({
      id: In(workerIds),
    });

    return pageData;
  }

  async checkCollection(userId: number, workerId: number) {
    const data = await this.bizCustomerWorkerCollectionEntity.findOneBy({
      userId,
      workerId,
    });

    return Boolean(data);
  }

  async collection(userId: number, workerId: number) {
    const p = {
      userId,
      workerId,
    };
    const data = await this.bizCustomerWorkerCollectionEntity.findOneBy(p);

    if (data) {
      await this.bizCustomerWorkerCollectionEntity.delete(data.id);
      return false;
    } else {
      await this.bizCustomerWorkerCollectionEntity.insert(p);
      return true;
    }
  }
}
